# 文件操作的常规步骤
# 1.打开文件
f = open("../resources/file.txt","r",encoding="utf-8")
# 2.操作文件(读取/写入)
content = f.read()
print(content)
# 3.关闭文件
f.close()

print("=" * 50)
# 使用with语句打开文件
# 一次性读取整个文件
with open("../resources/file.txt","r",encoding="utf-8") as f:
    content = f.read()
    print(content)

print("=" * 50)
# 按行读取文件
with open("../resources/file.txt","r",encoding="utf-8") as f:
    for line in f:
        print(line)

print("================")
# 按行读取存入列表中
with open("../resources/file.txt","r",encoding="utf-8") as f:
    # 一次性读取所有行放到列表中
    lines = f.readlines()

print("=" * 50)
# 读取指定长度的内容
with open("../resources/file.txt","r",encoding="utf-8") as f:
    content = f.read(5) # 读取前5个字符
    print(content)

print("=" * 50)
# 文件写入
# 覆盖写入
with open("../resources/demo.txt","w",encoding="utf-8") as f:
    f.write("hello Python")
    f.write("\n")
    f.write("你好，世界")


# 追加写入
with open("../resources/demo.txt","a",encoding="utf-8") as f:
    f.write("\n")
    f.write("这是追加写入的内容")

print("=" * 50)
# 字符串的编码与解码
s = "你好，这里一行文本"
# 字符串 -> bytes   编码
bytes_data = s.encode("utf-8")
print(bytes_data)
# bytes -> 字符串   解码
decode_data = bytes_data.decode("utf-8")
print(decode_data)

# 处理二进制文件
# 读取二进制文件
with open("../resources/image.png","rb") as f:
    bytes_data = f.read()
    print(bytes_data)


# 写入二进制文件
with open("../resources/image2.png","wb") as f:
    f.write(bytes_data)
    print("写入完成")

# 文件复制
with open("../resources/image.png","rb") as f:
    with open("../resources/image3.png","wb") as f2:
        while True:
            # 每次读取1024个字节数据
            data = f.read(1024)
            if not data:
                break
            f2.write(data)
    print("复制完成")
